// 用户相关的api
const express = require("express");
const router = express.Router();
// 引入加密bcrypt库
const bcrypt = require("bcrypt");
// 引入jwt，生成token
const jwt = require("jsonwebtoken");
// 引入mongodb.secretOrKey
const keys = require("../config/mongodb");
// 引入user
const User = require("../models/User");

router.get("/", (req, res) => {
	res.send("Hello World!!");
});
/* $route POST api/users/login
 * @desc 返回token jwt
 * @access public
 * 后台管理员登录
 */
router.post("/login", (req, res) => {
	console.log(req.body);
	const email = req.body.email;
	const password = req.body.password;
	User.findOne({ email }).then((user) => {
		if (!user) {
			return res.status(404).json("用户不存在！");
		} else {
			bcrypt.compare(password, user.password).then((isMatch) => {
				if (isMatch) {
					// 密码匹配成功
					// 生成token
					const rule = {
						id: user.id,
						name: user.name,
						avatar: user.avatar,
						isadmin: user.isadmin,
						isalladmin: user.isalladmin,
					};
					jwt.sign(
						rule,
						keys.secretOrKey,
						{ expiresIn: 7200 },
						(err, token) => {
							if (err) throw err;
							res.json({
								success: true,
								token: "Bearer " + token,
							});
						}
					);
				} else {
					return res.status(400).json("密码错误！");
				}
			});
		}
	});
});

module.exports = router;
